import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Switch, Route, Redirect } from 'react-router-dom';
import routesConfig from './config';

class Routes extends Component {
  render() {
    const { fnRouterChange } = this.props;
    const route = r => {
      const Component = r.component;
        return (
          <Route
            key={r.route || r.key}
            exact
            path={r.route || r.key}
            render={props => {
              const reg = /\?\S*/g;
              // 匹配?及其以后字符串
              const queryParams = window.location.hash.match(reg);
              // 去除?的参数
              const { params } = props.match;
              Object.keys(params).forEach(key => {
                params[key] = params[key] && params[key].replace(reg, '');
              });
              props.match.params = { ...params };
              const merge = { ...props, query: queryParams ? JSON.parse(queryParams[0]) : {} };
              // 回传route配置
              /* eslint-disable-next-line */
              fnRouterChange?.(r);
              return <Component {...merge} />
            }}
          />
        )
    }
    return (
      <Switch>
        {
          Object.keys(routesConfig).map(key =>
            routesConfig[key].map(r => {
              return r.component ? route(r) : r.subs.map(r => route(r));
            })
          )
        }
        <Route render={() => <Redirect to="/404" />} />
      </Switch>
    )
  }
};

export default connect(state => ({
  user: state.user
}))(Routes);
